package com.xbongbong.paas.help;

import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.OptionalRangeEntity;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.OptionalRangeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.pojo.dto.ProcessNodeTaskGetDTO;
import com.xbongbong.paas.pojo.dto.UserFormPermissionDTO;
import com.xbongbong.paas.pojo.dto.UserGetDTO;
import com.xbongbong.paas.pojo.vo.UserFormPermissionVO;
import com.xbongbong.paas.pojo.vo.UserGetVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.sys.domain.entity.ProPermissionEntity;
import com.xbongbong.sys.domain.entity.RoleEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.ProPermissionModel;
import com.xbongbong.sys.model.RoleModel;
import com.xbongbong.sys.model.UserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
public class UserInfoHelp {

    private static final Logger LOG = LoggerFactory.getLogger(UserInfoHelp.class);

    @Resource
    private UserModel userModel;
    @Resource
    private RoleModel roleModel;
    @Resource
    private ProPermissionModel proPermissionModel;

    public UserFormPermissionVO getUserFormPermissionInternal(String corpid, String userId, Long appId, Long menuId) throws XbbException {
        UserFormPermissionDTO userFormPermissionDTO = new UserFormPermissionDTO();
        userFormPermissionDTO.setCorpid(corpid);
        userFormPermissionDTO.setUserId(userId);
        userFormPermissionDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
        userFormPermissionDTO.setAppId(appId);
        userFormPermissionDTO.setMenuId(menuId);

        return getUserFormPermission(userFormPermissionDTO);
    }

    public UserFormPermissionVO getUserFormPermission(UserFormPermissionDTO userFormPermissionDTO) throws XbbException {
        return userModel.getUserFormPermission(userFormPermissionDTO.getCorpid(), userFormPermissionDTO.getUserId(), userFormPermissionDTO.getAppId(), userFormPermissionDTO.getMenuId());
    }

    /**
     * 将某个用户对应的角色id放入角色id集合 roleIdSet中
     * @param roleIds 某个用户表中的roleIds |1|2|格式
     * @param roleIdSet 角色id集合
     */
    public void formatRoleIdSet(String roleIds, Set<Integer> roleIdSet) {
        if (StringUtil.isEmpty(roleIds)) {
            // roleIds为空 异常数据可以记点日志
            return;
        }
        String[] roleIdArr = roleIds.split("\\|");
        for(String roleId : roleIdArr) {
            if(StringUtil.isEmpty(roleId)) {
                continue;
            }
            roleIdSet.add(Integer.valueOf(roleId));
        }
    }



    public UserGetVO getUserInfoByTargetUserId(UserGetDTO userGetDTO) throws XbbException {
        String corpid = userGetDTO.getCorpid();
        List<String> userIds = userGetDTO.getTargetUserId();
        return getUserInfoByTargetUserId(corpid, userIds);
    }

    public UserGetVO getUserInfoByTargetUserId(String corpid, List<String> userIds) throws XbbException {
        UserGetVO userGetVO = new UserGetVO();
        try {
            List<UserEntity> users = userModel.findEntitysByUserIds(userIds, corpid);
            //用户不存在
            if(users == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.USER_NOT_EXIST);
            }
            List<UserVO> userList = new ArrayList<>();
            List<Integer> roleIds = new ArrayList<>();
            // 加个-2防止用户有-1
            roleIds.add(-2);
            ProPermissionEntity byAlias = proPermissionModel.getByAlias(ProPermissionAliasEnum.CUSTOMER_DUPLICATE.getAlias());
            if (byAlias != null) {
                // 查出有客户查重权限的角色
                Integer id = byAlias.getId();
                Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                param.put("corpid", corpid);
                param.put("del", DelEnum.NORMAL.getDel());
                param.put("isUse", BasicConstant.ONE);
                param.put("permissionsLike", "|" + id + "|");
                List<RoleEntity> entitys = roleModel.findEntitys(param);
                entitys.forEach(item -> roleIds.add(item.getId()));
            }
            //暂时这样处理下
            List<Integer> clueDuplicateRoleIds = new ArrayList<>();
            // 加个-2防止用户有-1
            clueDuplicateRoleIds.add(-2);
            ProPermissionEntity clueDuplicate = proPermissionModel.getByAlias(ProPermissionAliasEnum.CLUE_DUPLICATE.getAlias());
            if (clueDuplicate != null) {
                // 查出有线索查重权限的角色
                Integer id = clueDuplicate.getId();
                Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                param.put("corpid", corpid);
                param.put("del", DelEnum.NORMAL.getDel());
                param.put("isUse", BasicConstant.ONE);
                param.put("permissionsLike", "|" + id + "|");
                List<RoleEntity> entitys = roleModel.findEntitys(param);
                entitys.forEach(item -> clueDuplicateRoleIds.add(item.getId()));
            }
            List<Integer> contactDuplicateRoleIds = new ArrayList<>();
            // 加个-2防止用户有-1
            clueDuplicateRoleIds.add(-2);
            ProPermissionEntity contactDuplicate = proPermissionModel.getByAlias(ProPermissionAliasEnum.CONTACT_DUPLICATE.getAlias());
            if (contactDuplicate != null) {
                // 查出有联系人查重权限的角色
                Integer id = contactDuplicate.getId();
                Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                param.put("corpid", corpid);
                param.put("del", DelEnum.NORMAL.getDel());
                param.put("isUse", BasicConstant.ONE);
                param.put("permissionsLike", "|" + id + "|");
                List<RoleEntity> entitys = roleModel.findEntitys(param);
                entitys.forEach(item -> contactDuplicateRoleIds.add(item.getId()));
            }
            for (UserEntity userEntity: users) {
                //用户信息
                UserVO userVO = new UserVO();
                BeanUtil.copyProperties(userEntity, userVO);
                userList.add(userVO);
                roleIds.retainAll(userEntity.roleIdsToList());
                if(roleIds.size() > 0) {
                    userVO.setCustomerDuplicate(true);
                }
                clueDuplicateRoleIds.retainAll(userEntity.roleIdsToList());
                if (!clueDuplicateRoleIds.isEmpty()) {
                    userVO.setClueDuplicate(true);
                }
                contactDuplicateRoleIds.retainAll(userEntity.roleIdsToList());
                if (!contactDuplicateRoleIds.isEmpty()) {
                    userVO.setContactDuplicate(true);
                }
            }
            userGetVO.setUserList(userList);
        } catch (XbbException xe) {
            //业务异常继续往外抛出
            throw xe;
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.help.UserInfoHelp.getUserInfoByTargetUserId 执行出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        return userGetVO;
    }

    /**
     * 获取用户
     * @param optionalRangeList 可选范围
     * @param processNodeTaskGetDTO 封装对象
     * @return 返回用户列表
     * @throws XbbException
     */
    public List<UserVO> getUserList(List<OptionalRangeEntity> optionalRangeList, ProcessNodeTaskGetDTO processNodeTaskGetDTO) throws XbbException{
        List<UserVO> resultUserList = new ArrayList<>();
        try {
            List<UserVO> userList = new ArrayList<>();
            List<String> roleIdList = new ArrayList<>();
            List<String> departmentIdList = new ArrayList<>();
            List<String> userIdList = new ArrayList<>();
            for(OptionalRangeEntity user: optionalRangeList) {
                if(user.getProperty().equals(OptionalRangeEnum.DEPT.getValue())){
                    departmentIdList.add(user.getId());
                } else if (user.getProperty().equals(OptionalRangeEnum.ROLE.getValue())){
                    roleIdList.add(user.getId());
                } else {
                    userIdList.add(user.getId());
                }
            }
            if(!userIdList.isEmpty()) {
                UserGetDTO userGetDTO = new UserGetDTO();
                BeanUtil.copyProperties(processNodeTaskGetDTO, userGetDTO);
                userGetDTO.setTargetUserId(userIdList);
                UserGetVO userGetVO = getUserInfoByTargetUserId(userGetDTO);
                if(userGetVO != null) {
                    userList = userGetVO.getUserList();
                }
            }
            // 获取部门下的用户
            if (!departmentIdList.isEmpty()) {
                Map<String, Object> departmentParams = BeanUtil.convertBean2Map(processNodeTaskGetDTO, true);
                departmentParams.put("depIdIn", departmentIdList);
                List<UserEntity> userListByDepartmentId = userModel.findEntitys(departmentParams);
                if(userListByDepartmentId == null) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.USER_NOT_EXIST);
                }
                for (UserEntity userEntity : userListByDepartmentId) {
                    //用户信息
                    UserVO userVO = new UserVO();
                    BeanUtil.copyProperties(userEntity, userVO);
                    userList.add(userVO);
                }
            }
            // 获取角色中的用户
            if(!roleIdList.isEmpty()){
                Map<String, Object> roleParams = BeanUtil.convertBean2Map(processNodeTaskGetDTO, true);
                roleParams.put("roleIdIn", roleIdList);
                List<UserEntity> userListByRoleId = userModel.findEntitys(roleParams);
                if(userListByRoleId == null) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.USER_NOT_EXIST);
                }
                for (UserEntity item : userListByRoleId) {
                    //用户信息
                    UserVO userVO = new UserVO();
                    BeanUtil.copyProperties(item, userVO);
                    userList.add(userVO);
                }
            }
            // 去重
            if(!userList.isEmpty()){
                Map<String, UserVO> userMap = new HashMap<>(userList.size());
                userList.forEach((item)->{
                    userMap.put(item.getUserId(), item);
                });
                Iterator iterator = userMap.keySet().iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next().toString();
                    UserVO userVO = userMap.get(key);
                    resultUserList.add(userVO);
                }
            }
        }catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("userHelp.getUserList根据可选范围获取用户出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return resultUserList;
    }

    public List<UserVO> getUserList(List<OptionalRangeEntity> optionalRangeList, String corpid) throws XbbException{
        List<UserVO> resultUserList = new ArrayList<>();
        try {
            List<UserVO> userList = new ArrayList<>();
            List<String> roleIdList = new ArrayList<>();
            List<String> departmentIdList = new ArrayList<>();
            List<String> userIdList = new ArrayList<>();
            for(OptionalRangeEntity user: optionalRangeList) {
                if(user.getProperty().equals(OptionalRangeEnum.DEPT.getValue())){
                    departmentIdList.add(user.getId());
                } else if (user.getProperty().equals(OptionalRangeEnum.ROLE.getValue())){
                    roleIdList.add(user.getId());
                } else {
                    userIdList.add(user.getId());
                }
            }
            if(!userIdList.isEmpty()) {
                UserGetVO userGetVO = getUserInfoByTargetUserId(corpid, userIdList);
                if(userGetVO != null) {
                    userList = userGetVO.getUserList();
                }
            }
            // 获取部门下的用户
            if (!departmentIdList.isEmpty()) {
                Map<String, Object> departmentParams = new HashMap<>();
                departmentParams.put(ParameterConstant.CORPID, corpid);
                departmentParams.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
                departmentParams.put("depIdIn", departmentIdList);
                List<UserEntity> userListByDepartmentId = userModel.findEntitys(departmentParams);
                if(userListByDepartmentId == null) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.USER_NOT_EXIST);
                }
                for (UserEntity userEntity : userListByDepartmentId) {
                    //用户信息
                    UserVO userVO = new UserVO();
                    BeanUtil.copyProperties(userEntity, userVO);
                    userList.add(userVO);
                }
            }
            // 获取角色中的用户
            if(!roleIdList.isEmpty()){
                Map<String, Object> roleParams = new HashMap<>();
                roleParams.put(ParameterConstant.CORPID, corpid);
                roleParams.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
                roleParams.put("roleIdIn", roleIdList);
                List<UserEntity> userListByRoleId = userModel.findEntitys(roleParams);
                if(userListByRoleId == null) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.USER_NOT_EXIST);
                }
                for (UserEntity item : userListByRoleId) {
                    //用户信息
                    UserVO userVO = new UserVO();
                    BeanUtil.copyProperties(item, userVO);
                    userList.add(userVO);
                }
            }
            // 去重
            if(!userList.isEmpty()){
                Map<String, UserVO> userMap = new HashMap<>(userList.size());
                userList.forEach((item)->{
                    userMap.put(item.getUserId(), item);
                });
                Iterator iterator = userMap.keySet().iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next().toString();
                    UserVO userVO = userMap.get(key);
                    resultUserList.add(userVO);
                }
            }
        }catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("userHelp.getUserList根据可选范围获取用户出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return resultUserList;
    }
}


